package com.iotechn.uninotify.service.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iotechn.uninotify.domain.DeveloperDO;
import com.iotechn.uninotify.domain.DeveloperUserDO;
import com.iotechn.uninotify.exception.NotifyExceptionDefinition;
import com.iotechn.uninotify.exception.NotifyServiceException;
import com.iotechn.uninotify.exception.ServiceException;
import com.iotechn.uninotify.mapper.DeveloperMapper;
import com.iotechn.uninotify.mapper.DeveloperUserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/12/26
 * Time: 16:04
 */
@Service
public class DeveloperBizService {

    @Autowired
    private DeveloperMapper developerMapper;

    @Autowired
    private DeveloperUserMapper developerUserMapper;

    private static final Logger logger = LoggerFactory.getLogger(DeveloperBizService.class);

    public DeveloperDO getDeveloperByAppId(String appId) throws ServiceException  {
        DeveloperDO developerDO = developerMapper.selectOne(new QueryWrapper<DeveloperDO>().eq("app_id", appId));
        if (developerDO == null) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_APP_ID_NOT_EXIST);
        }
        return developerDO;
    }

    public int register(String appId, String userId, String openId) throws ServiceException {
        Integer count = developerUserMapper.selectCount(new QueryWrapper<DeveloperUserDO>().eq("user_id", appId));
        if (count > 0) {
            logger.warn("[用户已经录入] 重复扫码");
            return 1;
        }
        Date now = new Date();
        DeveloperUserDO userDO = new DeveloperUserDO();
        userDO.setAppId(appId);
        userDO.setOpenId(openId);
        userDO.setUserId(userId);
        userDO.setGmtCreate(now);
        userDO.setGmtUpdate(now);
        int insert = developerUserMapper.insert(userDO);
        if (insert > 0) {
            return 0;
        }
        return 2;
    }

    public DeveloperUserDO getUserById(String appId, String userId) throws ServiceException {
        DeveloperUserDO userDO = developerUserMapper.selectOne(new QueryWrapper<DeveloperUserDO>().eq("user_id", userId).eq("app_id", appId));
        if (userDO == null) {
            throw new NotifyServiceException(NotifyExceptionDefinition.NOTIFY_USER_NOT_EXIST);
        }
        return userDO;
    }

}
